package section

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetSectionBlogListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetSectionBlogListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSectionBlogListLogic {
	return &GetSectionBlogListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetSectionBlogListLogic) GetSectionBlogList(in *backend.BaseListReq) (*backend.SectionBlogListResp, error) {
	// logrus.Info(fmt.Sprintf("GetSectionList BaseListReq: %+v", in))
	// Limit:2  Preload:"section:Id,Title,Subtitle,PicId,PicUrl"  Filter:"Status,equalTo:1;Type,equalTo:1"  VisitorId:10021  PlatformId:1

	if in.Filter == nil || len(*in.Filter) == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}
	preloadMap, eagerLoadMap := modelx.ParsePreloadAndEagerLoad(in.Preload, in.EagerLoad)
	// logrus.Info(fmt.Sprintf("GetSectionBlogList preloadMap: %+v", preloadMap))
	// map[section:[Id Title Subtitle PicId PicUrl]]
	// logrus.Info(fmt.Sprintf("GetSectionBlogList eagerLoadMap: %+v", eagerLoadMap))
	// map[]

	bannerEntityName := model.RpcEntityNames.Section
	if _, ok := model.RpcEntityPreloadMap[bannerEntityName]; !ok {
		return &backend.SectionBlogListResp{}, nil
	}

	bannerRepositoryName := model.RepositoryNames.Section
	columnMap, ok := model.RepositoryPreloadMap[bannerRepositoryName]
	if !ok {
		return &backend.SectionBlogListResp{}, nil
	}

	var selectCols []string
	if preloadFields, ok := preloadMap[bannerEntityName]; ok {
		selectCols = modelx.ParseSelectColumns(preloadFields, columnMap)
	}

	filterMap := modelx.ParseFilter(in.Filter, columnMap)
	// logrus.Info(fmt.Sprintf("GetSectionList filterMap: %+v", filterMap))
	// map[status:map[equalTo:[1]] type:map[equalTo:[1]]]
	if filterMap == nil {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	orderBy := modelx.ParseSorter(in.Sorter, columnMap)
	// logrus.Info(fmt.Sprintf("GetSectionList orderBy: %s", orderBy))
	//
	if len(orderBy) == 0 {
		orderBy = model.SectionColumns.Sort
	}

	res, count, err := l.svcCtx.Section.GetList(l.ctx, model.M{
		"offset":  in.Offset,
		"limit":   in.Limit,
		"orderBy": orderBy,
		"select":  strings.Join(selectCols, ","),
	}, 2, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}
	hasNextPage, hasPreviousPage := modelx.ParseCount(count)
	resp := &backend.SectionBlogListResp{
		HasNextPage:     &hasNextPage,
		HasPreviousPage: &hasPreviousPage,
	}

	var total int64
	if len(res) > 0 {
		var ids []any
		for _, v := range res {
			ids = append(ids, v.ID)
		}

		subEntitySettingMap := make(map[string]map[string]*model.ColumnSetting)
		if eagerLoadEntities, ok := eagerLoadMap[bannerEntityName]; ok {
			for _, entity := range eagerLoadEntities {
				if entity == "total" {
					_, total, err = l.svcCtx.Section.GetList(l.ctx, model.M{}, 0, filterMap)
					if err != nil {
						total = 0
					}
					continue
				}

				if entitySettingMap, ok := model.RpcEntityPreloadMap[entity]; ok {
					subEntitySettingMap[entity] = entitySettingMap
				}
			}
		}

		idMediaMap := make(map[uint64][]*backend.MediaInfo)
		backendMediaEntityName := model.RpcEntityNames.BackendMedia
		backendMediaRepositoryName := model.RepositoryNames.BackendMedia
		if _, ok := subEntitySettingMap[backendMediaEntityName]; ok {
			subPreloadFields, hasSubPreloadFields := preloadMap[backendMediaEntityName]
			subColumnMap, hasSubColumnMap := model.RepositoryPreloadMap[backendMediaRepositoryName]
			if hasSubPreloadFields && hasSubColumnMap {
				var subSelectCols = modelx.ParseSelectColumns(subPreloadFields, subColumnMap)
				subSelectCols = append(subSelectCols, model.AttachmentRelationshipColumns.ObjectID)

				subFilterMap := make(map[string]map[string][]any)
				subFilterMap[model.AttachmentRelationshipColumns.ObjectID] = map[string][]any{
					"in": ids,
				}
				subFilterMap[model.AttachmentRelationshipColumns.ObjectType] = map[string][]any{
					"equalTo": {globalkey.AttachmentLogTypeBanner},
				}
				list, _, err := l.svcCtx.Section.GetMedia(l.ctx, model.M{
					"orderBy": model.AttachmentRelationshipColumns.AttachmentOrder,
					"select":  strings.Join(subSelectCols, ","),
				}, -1, subFilterMap)
				if err != nil {
					return nil, err
				}

				if len(list) > 0 {
					for _, v := range list {
						idMediaMap[v.ObjectID] = append(idMediaMap[v.ObjectID], &backend.MediaInfo{
							Uid:       pointy.GetPointer(v.RelationshipID),
							Id:        pointy.GetPointer(strconv.FormatInt(int64(v.AttachmentID), 10)),
							Thumbnail: pointy.GetPointer(uint32(v.AttachmentThumbnail)),
							Order:     pointy.GetPointer(uint32(v.AttachmentOrder)),
							Uri:       pointy.GetPointer(v.AttachmentImageSource),
							Url:       pointy.GetPointer(v.AttachmentImageURL),
							AltText:   pointy.GetPointer(v.AttachmentImageAlt),
							MetaData:  pointy.GetPointer(v.AttachmentImageMeta),
						})
					}
				}
			}
		}

		idBlogIdsMap := make(map[uint64][]uint64)
		sectionBlogEntityName := model.RpcEntityNames.SectionPost
		sectionBlogRepositoryName := model.RepositoryNames.SectionPost
		if _, ok := subEntitySettingMap[sectionBlogEntityName]; ok {
			subPreloadFields, hasSubPreloadFields := preloadMap[sectionBlogEntityName]
			subColumnMap, hasSubColumnMap := model.RepositoryPreloadMap[sectionBlogRepositoryName]
			if hasSubPreloadFields && hasSubColumnMap {
				var subSelectCols = modelx.ParseSelectColumns(subPreloadFields, subColumnMap)
				subSelectCols = append(subSelectCols, model.SectionPostRelationshipColumns.SectionID)

				for _, id := range ids {
					subFilterMap := make(map[string]map[string][]any)
					subFilterMap[model.SectionPostRelationshipColumns.SectionID] = map[string][]any{
						"equalTo": {id},
					}
					list, _, err := l.svcCtx.Section.GetRelPostList(l.ctx, model.M{
						"limit":   in.Limit,
						"orderBy": model.SectionPostRelationshipColumns.Sort,
						"select":  strings.Join(subSelectCols, ","),
					}, 2, subFilterMap)
					if err != nil {
						return nil, err
					}
					if len(list) > 0 {
						var sectionId uint64
						var blogIds []uint64
						for _, v := range list {
							sectionId = v.SectionID
							blogIds = append(blogIds, v.PostID)
						}
						idBlogIdsMap[sectionId] = blogIds
					}
				}
			}

			for _, v := range res {
				var newMedia []*backend.MediaInfo
				if media, ok := idMediaMap[v.ID]; ok {
					newMedia = media[:]
				}
				var sort *uint32
				if v.Sort != uint16(globalkey.SystemDefaultSort) {
					sort = pointy.GetPointer(uint32(v.Sort))
				}
				var blogIds []uint64
				if pids, ok := idBlogIdsMap[v.ID]; ok {

					blogIds = pids[:]
				}
				resp.List = append(resp.List, &backend.SectionBlogInfo{
					Id:         pointy.GetPointer(v.ID),
					Type:       pointy.GetPointer(uint32(v.Type)),
					Title:      pointy.GetPointer(v.Title),
					Subtitle:   pointy.GetPointer(v.Subtitle),
					PicId:      pointy.GetPointer(v.PicID),
					PicUrl:     pointy.GetPointer(v.PicURL),
					Sort:       sort,
					Status:     pointy.GetPointer(uint32(v.Status)),
					CreatedAt:  pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
					UpdatedAt:  pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
					DeletedAt:  pointy.GetPointer(modelx.FormatNullDotTime(v.DeletedAt, "")),
					ObjectIds:  blogIds,
					ObjectType: pointy.GetPointer(uint64(v.Type)),
					Media:      newMedia,
				})
			}
		}
	}
	resp.Total = uint64(total)
	return resp, nil
}
